<?php

namespace App\Http\Controllers\admin\sender;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\User;
use App\Models\User_info;

use App\Models\Sender;
use App\Models\Store;

class SenderController extends Controller
{
    //
    public function index()
    {
        $data = Sender::all(['name','id','status']);

        foreach ($data as $v){

            $v['store'] = Sender::find($v['id'])->store->name;
        }

        return view('admin.sender.sender',['list'=>$data]);
    }

    public function create()
    {
        $list = Store::all(['name','id']);
       return view('admin.sender.senderAdd',['list'=>$list]);
    }

    public function store(Request $request)
    {
        $sender = new Sender();
        $data = $request->except('_token','select','password');

        $data['password'] = md5($request->input('password'));
        $user = new User();

        $user->username = time();
        $user->password = 3;
        $user->class = 3;

        $uinsert = $user->save();

        $userid = $user->id;

        $userinfo = new User_info();

        $userinfo->user_id = $userid;

        $userinfo->save();

        $data['user_id'] = $user->id;


        //dd($data);

        $insert = $sender->create($data);

        $bool = $insert->save();

        if($bool){
            return redirect('/admin/sender');
        }else{
            return null;
        }

    }

    public function edit($id)
    {
        $list = sender::find($id);

        return view('admin.sender.senderEdit',['list'=>$list]);
    }

    public function status(Request $request)
    {
        $id = $request->input('id');

        $data = Sender::find($id);

        $data->status = $data->status==3?2:3;

        $bool = $data->save();

        if($bool){
            return 1;
        }else{
            return 0;
        }
    }

    public function update($id,Request $request)
    {
        $sender = new sender();
        $data = $request->except('_token','_method','select');


        $bool = $sender->where('id',$id)->update($data);

        if($bool){
            return redirect('/admin/sender');
        }else{
            return null;
        }

    }

    public function userInfo(Request $request)
    {
        $id = $request->input('id');

        $data = Sender::find($id,['name','idcard','phone','address']);

        return $data;
    }
}
